package ch3

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type Greeting struct {
	Name    string `json:"name"`
	Message string `json:"message"`
}

func greetingHandler(w http.ResponseWriter, r *http.Request) {
	greeting := Greeting{}

	query := r.URL.Query()
	greeting.Message = query["message"][0]
	fmt.Fprintf(w, "greeting Message is: %s", greeting.Message)
}


// 可以用这样的命令测试
// curl --location 'localhost:8081/greeting1' \
// --header 'Content-Type: application/x-www-form-urlencoded' \
// --data-urlencode 'name=world' \
// --data-urlencode 'message=hello'
func greetingHandler1(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	_ = r.ParseForm()
	message := r.Form.Get("message")
	name := r.Form.Get("name")
	greeting := Greeting{}
	greeting.Message = message
	greeting.Name = name
	// 这里仅仅是打印，实际上还可以转换成json
	// fmt.Fprintf(w, "greeting Message is: %s", greeting.Message)
	var res = make(map[string]interface{})
	// 仅支持Post
	for k, v := range r.PostForm {
		res[k] = v
	}
	bytes, _ := json.Marshal(res)
	_, _ = w.Write(bytes)

}

func Serve4() {
	mux := http.NewServeMux()
	//注册处理器函数
	mux.HandleFunc("/greeting", greetingHandler)
	mux.HandleFunc("/greeting1", greetingHandler1)

	server := &http.Server{
		Addr:    ":8081",
		Handler: mux,
	}

	if err := server.ListenAndServe(); err != nil {
		log.Fatal(err)
	}
	
}
